package com.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author B站：爱计算机的小天才 QQ167775665
 * @Date 2022/08/25
 **/

public class CommonUtil {

    private static final String RANDOMSTRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    private static final String  NUMBERSTRIN = "0123456789";

    /**
     * @Title: unicodeEncode
     * @Description: unicode编码 将中文字符转换成Unicode字符
     * @param string
     * @return
     */
    public static String unicodeEncode(String string) {
        char[] utfBytes = string.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }


    /**
     * MD5加密
     */
    public static String MD5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
            }

            return sb.toString().toUpperCase();
        } catch (Exception exception) {
        }
        return null;
    }

    /**
     * 获取随机数
     */
    public static String getRandomCode(int length) {
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i=0; i<length; i++){
            stringBuffer.append(NUMBERSTRIN.charAt(random.nextInt(NUMBERSTRIN.length())));
        }
        return stringBuffer.toString();
    }

    /**
     * 获得时间戳
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis();
    }


    /**
     * UUID 32位的生成
     */
    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-","").substring(0, 32);
    }


    /**
     * 随机生成字符串
     */
    public static String getStringRandom(int length) {
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for(int i=0; i<length; i++){
            stringBuffer.append(RANDOMSTRING.charAt(random.nextInt(RANDOMSTRING.length())));
        }
        return stringBuffer.toString();
    }
}
